
#include "StorexServer.h"

using boost::asio::ip::tcp;


StorexServer::StorexServer(int port, int thread_pool_size) :
	connectionCounter(0),
	connectionTable(new ConnectionTable()),
	configHandler(new ConfigHandler()),
	storexEngine(configHandler, connectionTable),
	threadNum(thread_pool_size),
	acceptor(ioService,tcp::endpoint(tcp::v4(), port)),
	newConnection(new Connection(ioService, connectionCounter++, connectionTable, storexEngine))
{
	acceptor.async_accept(newConnection->getSocket(), boost::bind(&StorexServer::handle_accept, this, boost::asio::placeholders::error));

}


void StorexServer::run() {

ioService.run();
/*
	// Create a pool of threads to run all of the io_services.
	std::vector<boost::shared_ptr<boost::thread> > threads;
	for (std::size_t i = 0; i < threadNum; ++i) {
		boost::shared_ptr<boost::thread> thread(new boost::thread(boost::bind(&boost::asio::io_service::run, &ioService), (void*)NULL)); //riga adattata
		threads.push_back(thread);
	}
	// Wait for all threads in the pool to exit.
	for (std::size_t i = 0; i < threads.size(); ++i){
		threads[i]->join();
	}
*/
}


void StorexServer::stop() {
	ioService.stop();
}


void StorexServer::handle_accept(const boost::system::error_code& error) {

	if (!error) newConnection->start();

	newConnection.reset(new Connection(ioService, connectionCounter++, connectionTable, storexEngine));
	acceptor.async_accept(newConnection->getSocket(), boost::bind(&StorexServer::handle_accept, this, boost::asio::placeholders::error));
}




